package form;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.api.skin.SubstanceSaharaLookAndFeel;

import check_form.CheckString;
import chucnang.BanHang;
import chucnang.MuaHang;



import trangchu.UtilDelegate;
import javax.swing.event.CaretListener;
import javax.swing.event.CaretEvent;


public class FormBanHang extends JDialog implements ActionListener {

	private JPanel plCenter,plSouth;
	public JTextField txtSoLuong;
	public JTextField txtThanhTien;
	public JTextField txtDonGia;
	public JTextField txtDonVi;
	public JComboBox cmbMaHang;
	public JComboBox cmbTenHang;
	public JTextField txtKhoHang;
	private JButton btnLuu,btnDong;
	ResultSet rs;
	PreparedStatement st;
	Connection con =UtilDelegate.getConnection();

	private BanHang banhang;
	private CheckString check;
	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame.setDefaultLookAndFeelDecorated(true);
                LookAndFeel laf = new SubstanceSaharaLookAndFeel();
                SubstanceLookAndFeel.setToUseConstantThemesOnDialogs(true);
                //UIManager.put(SubstanceLookAndFeel.TABBED_PANE_CLOSE_BUTTONS_PROPERTY,Boolean.TRUE);
                UIManager.put(SubstanceLookAndFeel.SHOW_EXTRA_WIDGETS, Boolean.TRUE);
                JFrame.setDefaultLookAndFeelDecorated(false);
                JDialog.setDefaultLookAndFeelDecorated(true);
                try {
                        UIManager.setLookAndFeel(laf);
                        FormBanHang f = new FormBanHang(null);
    					f.setResizable(false);
                } catch (UnsupportedLookAndFeelException e) {
                        e.printStackTrace();
                }
            }
        });
		
	}


	public FormBanHang(BanHang frame) {
		
		this.setTitle("Cập nhật hàng hóa");
		this.banhang = frame;
		this.setModal(true);
		setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
		Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
	    setBounds((screenSize.width-470)/2, (screenSize.height-211)/2, 470, 196);
		//setBounds(100, 100, 470, 211);
		plCenter = new JPanel();
		plCenter.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(plCenter);
		plCenter.setLayout(new MigLayout("", "[][grow][][][][][grow][][grow]", "[][][][][][][]"));
		
		
		JLabel lblMaHang = new JLabel("Mã Hàng");
		plCenter.add(lblMaHang, "cell 0 2,alignx left");
		
		cmbMaHang = new JComboBox();
		plCenter.add(cmbMaHang, "cell 1 2 3 1,growx");
		Dimension d = cmbMaHang.getPreferredSize();
		cmbMaHang.setPreferredSize(new Dimension(200, d.height));
		
		JLabel lblKhoHang = new JLabel("Kho Hàng");
		plCenter.add(lblKhoHang, "cell 5 2,alignx left");
		
		txtKhoHang = new JTextField();
		plCenter.add(txtKhoHang, "cell 6 2 3 1,growx");
		txtKhoHang.setColumns(10);
		txtKhoHang.setEditable(false);
		
		JLabel lblTenHang = new JLabel("Tên Hàng");
		plCenter.add(lblTenHang, "cell 0 3,alignx left");
		
		cmbTenHang = new JComboBox();
		plCenter.add(cmbTenHang, "cell 1 3 8 1,growx");
		
		
		JLabel lblDonGia = new JLabel("Đơn Giá");
		plCenter.add(lblDonGia, "cell 0 4,alignx left");
		
		txtDonGia = new JTextField();
		plCenter.add(txtDonGia, "cell 1 4 3 1,growx");
		txtDonGia.setColumns(10);
		txtDonGia.setEditable(false);
		
		JLabel lblSoLuong = new JLabel("Số Lượng");
		plCenter.add(lblSoLuong, "cell 5 4,alignx left");
		
		txtSoLuong = new JTextField();
		txtSoLuong.addCaretListener(new CaretListener() {
			public void caretUpdate(CaretEvent e) {
				txtSoLuong.setBackground(Color.white);
				if(CheckString.OnlyNumber(txtSoLuong.getText(), 5, 1)==true){
					String b = txtDonGia.getText();
					Integer n1 = Integer.parseInt(b);
					String c = txtSoLuong.getText();
					Integer n2 = Integer.parseInt(c);
					int a = n1*n2;
					String d = String.valueOf(a); 
					txtThanhTien.setText(d);
				}
			}
		});
		plCenter.add(txtSoLuong, "cell 6 4 3 1,growx");
		txtSoLuong.setColumns(10);
		
		
		
		
		JLabel lblDonVi = new JLabel("Đơn Vị");
		plCenter.add(lblDonVi, "cell 0 5,alignx left");
		
		txtDonVi = new JTextField();
		plCenter.add(txtDonVi, "cell 1 5 3 1,growx");
		txtDonVi.setColumns(10);
		txtDonVi.setEditable(false);
		
		JLabel lblThanhTien = new JLabel("Thành Tiền");
		plCenter.add(lblThanhTien, "cell 5 5,alignx left");
		
		txtThanhTien = new JTextField();
		plCenter.add(txtThanhTien, "cell 6 5 3 1,growx");
		txtThanhTien.setColumns(10);
		txtThanhTien.setEditable(false);
		
		plSouth = new JPanel();
		plCenter.add(plSouth,"cell 6 6 3 1,growx");
		plSouth.setLayout(new FlowLayout(FlowLayout.RIGHT));
		btnLuu = new JButton("Lưu",new ImageIcon("images/luu.gif"));
		btnDong = new JButton("Đóng",new ImageIcon("images/ketthuc.gif"));
		plSouth.add(btnLuu);
		plSouth.add(btnDong);
		btnLuu.addActionListener(this);
		btnDong.addActionListener(this);
		cmbMaHang.addActionListener(this);
		cmbTenHang.addActionListener(this);
		
		
	    
		Dbselect();
	}
	public void Dbselect(){
		DSJ_FormMuaHang data = new DSJ_FormMuaHang();
		Vector<DSJ_FormMuaHang> getMuaHangs = data.getUsers();
		for(int i=0;i<getMuaHangs.size();i++){
			cmbMaHang.addItem(getMuaHangs.get(i).getMaSP());
			cmbTenHang.addItem(getMuaHangs.get(i).getTenSP());
			txtDonVi.setText(getMuaHangs.get(0).getDonViSP());
			txtKhoHang.setText(getMuaHangs.get(0).getKho());
			txtDonGia.setText(getMuaHangs.get(0).getGiaBan());
		}
		
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if(e.getSource() == btnDong){
			dispose();
		}
		if(e.getSource() == cmbMaHang){
			try {
			       String sql = "select * from HangHoa join DonVi on HangHoa.DonViSP = DonVi.MaDV join DiaChiKho on HangHoa.Kho = DiaChiKho.MaK join NhomHang on HangHoa.NhomSP = NhomHang.MaNH WHERE MaSP = '" +cmbMaHang.getSelectedItem().toString() + "'";
			        st = con.prepareStatement(sql);
					ResultSet rs = st.executeQuery();
			        while(rs.next()){
			        	cmbTenHang.setSelectedItem(rs.getString("TenSP"));
			        	txtDonGia.setText(rs.getString("GiaBan"));
			        	txtDonVi.setText(rs.getString("TenDV"));
			        	txtKhoHang.setText(rs.getString("TenKho"));
			        	txtSoLuong.setText("0");
			        	txtThanhTien.setText("0");
			        	txtSoLuong.setBackground(Color.white);
			        }
			                       
			    } catch (SQLException ex) {
			       ex.printStackTrace();
			    }
		}
		if(e.getSource() == cmbTenHang){
			try {
			       String sql = "select * from HangHoa join DonVi on HangHoa.DonViSP = DonVi.MaDV join DiaChiKho on HangHoa.Kho = DiaChiKho.MaK join NhomHang on HangHoa.NhomSP = NhomHang.MaNH WHERE TenSP = N'" +cmbTenHang.getSelectedItem().toString() + "'";
			        st = con.prepareStatement(sql);
					ResultSet rs = st.executeQuery();
					
			        while(rs.next()){
			        	cmbMaHang.setSelectedItem(rs.getString("MaSP"));
			        	txtDonGia.setText(rs.getString("GiaBan"));
			        	txtDonVi.setText(rs.getString("TenDV"));
			        	txtKhoHang.setText(rs.getString("TenKho"));
			        	txtSoLuong.setText("0");
			        	txtThanhTien.setText("0");
			        	txtSoLuong.setBackground(Color.white);
			        }
			                       
			    } catch (SQLException ex) {
			       ex.printStackTrace();
			    }
		}
		
		if(e.getSource() == btnLuu){
			
			if(CheckString.OnlyNumber(txtSoLuong.getText(), 5, 1)==false){
				JOptionPane.showMessageDialog(btnLuu, "Lỗi nhập số lượng ! \n Vui lòng nhập lại.","alert",JOptionPane.OK_OPTION);
				txtSoLuong.setBackground(Color.RED);
				
			}else{
			//giam so luong
			DSJ_FormMuaHang data = new DSJ_FormMuaHang();
			data.setMaSP(cmbMaHang.getSelectedItem().toString());
			String getMuaHangs = data.selecthanghoa(data);			
			Integer n1 = Integer.parseInt(getMuaHangs);			
			String sl = txtSoLuong.getText();
			Integer n2 = Integer.parseInt(sl);
			int tong = n1-n2;
			String d = String.valueOf(tong);
			String donvi1 = txtDonVi.getText();
			
			if(tong>=0){
				
				if(CheckString.OnlyNumber(txtSoLuong.getText(), 5, 1)==true){
					int luu = JOptionPane.showConfirmDialog(btnLuu,  "Bạn có chắc muốn lưu không?", "alert", JOptionPane.YES_NO_OPTION);
					if(luu == JOptionPane.YES_OPTION){		
						
						DSJ_XuatHang delegate = new DSJ_XuatHang();
						DSJ_FormMuaHang person = new DSJ_FormMuaHang();
						DSJ_NhanVien nhanvien = new DSJ_NhanVien();
						DSJ_DieuKhoanThanhToan dieukhoan = new DSJ_DieuKhoanThanhToan();
						DSJ_KhachHang khachhang = new DSJ_KhachHang();
						DSJ_KhoHang kho = new DSJ_KhoHang();
						DSJ_DonVi donvi = new DSJ_DonVi();
						
						person.setMaSP(cmbMaHang.getSelectedItem().toString());
						person.setTenSP(cmbTenHang.getSelectedItem().toString());
						kho.setTenKho(txtKhoHang.getText());
						donvi.setTenDV(txtDonVi.getText());
						person.setGiaBan(txtDonGia.getText());
						person.setSoLuong(txtSoLuong.getText());
						person.setThanhTien(txtThanhTien.getText());
						nhanvien.setHoTenNV(banhang.cmbTenNV.getSelectedItem().toString());
						java.util.Date datengay =  banhang.dateStart.getDate();
						String datengaynhaphang = String.format("%1$td-%1$tm-%1$tY", datengay);
						person.setNgayNhapHang(datengaynhaphang);
						khachhang.setMaKH(banhang.cmbMa.getSelectedItem().toString());
						khachhang.setHoTenKH(banhang.cmbTenKH.getSelectedItem().toString());
						dieukhoan.setTenDK(banhang.cmbThanhToan.getSelectedItem().toString());
						java.util.Date datehan =  banhang.datehanthanhtoan.getDate();
						String datehanthanhtoan = String.format("%1$td-%1$tm-%1$tY", datehan);
						person.setHanThanhToan(datehanthanhtoan);	
						person.setChungTu(banhang.txtPhieu.getText());
						person.setGhiChu(banhang.txtGhiChu.getText());
						person.setLoaiChungTu(banhang.title.getTitle().toString());
						
						delegate.insertInto(person,nhanvien,dieukhoan,khachhang,kho,donvi);
						
						//giam so luong	
						data.setSoLuong(d);
						data.updatehanghoa(data);

						DSJ_XuatHang b = new DSJ_XuatHang();
						Vector list = b.getLoad();					
						
						Object[] oPerson = {
								list.get(0).toString(),
								list.get(1).toString(),
								list.get(2).toString(),
								list.get(3).toString(),
								list.get(4).toString(),
								list.get(5).toString(),
								list.get(6).toString(),
								list.get(7).toString()};
						
						banhang.model.insertRow(0, oPerson);
						banhang.model.fireTableDataChanged();
						
						banhang.btnSua.setEnabled(true);
						banhang.btnXoa.setEnabled(true);
						banhang.btnTaoMoi.setEnabled(true);
						banhang.getInfoConLai();
						banhang.getInfo();
						txtSoLuong.setBackground(Color.white);
						//dispose();
					}				
				}								
			}
			else if(tong<0){
				JOptionPane.showMessageDialog(btnLuu, "Số lượng trong kho còn : "+n1 +" "+ donvi1+"\n Vui lòng nhập thêm hàng.","Lỗi",JOptionPane.OK_OPTION);
				txtSoLuong.setBackground(Color.YELLOW);
				}
			}
		}
	}

}
